package com.graduate.examapp.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.graduate.examapp.entity.AddUserParam
import com.graduate.examapp.entity.StatusParam
import com.graduate.examapp.entity.Teacher
import com.graduate.examapp.entity.UserInfoFactory
import com.graduate.examapp.model.TeacherRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.MultipartBody

class TeacherViewModel : ViewModel() {
    val teacherLiveData = MutableLiveData<MutableList<Teacher>?>()

    val teacherDelMsgLiveData = MutableLiveData<String?>()
    val techerRepository = TeacherRepository()

    fun getTeacherList(insName: String) {
        if (insName.isNotBlank()) {
            viewModelScope.launch(Dispatchers.IO) {
                val teacherResponse = techerRepository.fetchTeacherData(insName)
                if (teacherResponse.code == LoginViewModel.REQUEST_OK) {
                    Log.d("TeacherViewModel", teacherResponse.data.toString())
                    teacherLiveData.postValue(teacherResponse.data)
                }
            }
        }
    }

    /**
     * 以文件形式导入教师信息
     */
    fun uploadTeacher(part: MultipartBody.Part) {
        viewModelScope.launch(Dispatchers.IO) {
            val response = techerRepository.addTeacherBatch(part)
            if (response.code == LoginViewModel.REQUEST_OK) {
                UserInfoFactory.loginData?.insName?.let { getTeacherList(it) }
            } else {
                teacherDelMsgLiveData.postValue(response.message)
            }
        }
    }

    /**
     * 删除教师
     */
    fun delTeacher(teacherDelParam: StatusParam, i: Int) {
        viewModelScope.launch(Dispatchers.IO) {

            val booleanResponse = techerRepository.delTeacher(teacherDelParam)
            if (booleanResponse.code == LoginViewModel.REQUEST_OK) {
                teacherDelMsgLiveData.postValue("删除成功")
                UserInfoFactory.loginData?.insName?.let {
                    getTeacherList(it)
                }
            } else {
                teacherDelMsgLiveData.postValue(booleanResponse.message)
            }
        }
    }

    fun changeTeacherStatus(statusParam: StatusParam) {
        viewModelScope.launch(Dispatchers.IO) {
            val response = techerRepository.changeStatus(statusParam)
        }
    }

    fun addTeacher(addUserParam: AddUserParam) {
        viewModelScope.launch(Dispatchers.IO) {
            val addTeacherResponse = techerRepository.addTeacher(addUserParam)
            if (addTeacherResponse.code ==LoginViewModel.REQUEST_OK) {
                teacherDelMsgLiveData.postValue("添加成功")
                //如何控制界面及时刷新？
                UserInfoFactory.loginData?.insName?.let { getTeacherList(it) }
            } else {
                teacherDelMsgLiveData.postValue(addTeacherResponse.message)
            }
        }
    }
}